package com.cn.sl.server.api.system.user.dao.rdb.impl

import com.cn.sl.server.api.system.user.dao.rdb.AdminUserDao
import com.cn.sl.server.api.system.user.model.entity.AdminUserEntity
import com.cn.sl.server.api.system.user.model.entity.QAdminUserEntity
import com.cn.sl.server.api.system.user.repository.AdminUserRepository
import com.cn.sl.server.common.dao.impl.SoftDeleteBaseDaoImpl
import com.cn.sl.server.common.model.QSoftDeleteEditableEntity
import com.querydsl.jpa.impl.JPAQueryFactory
import org.springframework.stereotype.Repository

@Repository
class AdminUserDaoImpl(
    val adminUserRepository: AdminUserRepository,
    val jpaQueryFactory: JPAQueryFactory
) : AdminUserDao, SoftDeleteBaseDaoImpl<AdminUserEntity, AdminUserRepository, AdminUserEntity>() {
    override fun findByUsername(username: String): AdminUserEntity? {
        return adminUserRepository.findFirstByUsernameAndDel(username)
    }

    override fun updatePassword(id: Long, password: String, salt: String) {
        jpaQueryFactory.update(entity)
            .set(entity.password, password)
            .set(entity.salt, salt)
            .where(entity.id.eq(id))
            .execute()
    }

    override fun findAllByUsername(username: String): List<AdminUserEntity> {
        return adminUserRepository.findAllByUsernameAndDel(username)
    }

    override fun findByUsernameAndIdNot(username: String, id: Long): AdminUserEntity? {
        return adminUserRepository.findFirstByUsernameAndIdNotAndDel(username, id)
    }

    override fun findByDepartmentId(id: Long): List<AdminUserEntity> {
        return adminUserRepository.findByDepartmentIdAndDel(id)
    }

    override fun findAllByDepartmentIdIn(departmentIds: List<Long>): List<AdminUserEntity> {
        return getRepository().findAllByDepartmentIdInAndDel(departmentIds)
    }

    override fun findByPhone(phone: String): AdminUserEntity? {
        return getRepository().findFirstByPhoneAndDel(phone)
    }

    override fun findByPhoneAndIdNot(phone: String, id: Long?): AdminUserEntity? {
        val query = jpaQueryFactory.selectFrom(entity)
            .where(entity.phone.eq(phone))
        if (id != null) {
            query.where(entity.id.ne(id))
        }
        return query.fetchFirst()
    }

    override fun getRepository(): AdminUserRepository {
        return adminUserRepository
    }

    override fun getEntity(): QSoftDeleteEditableEntity {
        return QAdminUserEntity.adminUserEntity._super
    }

    companion object {
        val entity: QAdminUserEntity = QAdminUserEntity.adminUserEntity
    }
}